/**
 * @description:
 * @file: auth.ts
 * @author: Evan
 * @date: 2025.04.08 11:05:44
 * @week: 周二
 * @version: V
 * */

import { defineStore } from 'pinia'
import { constantRoutes, asyncRoutes } from '@/router/routes'
import type { RouteItem } from '@/router/type'
export const separator = '\x1F'

/**
 * 根据权限过滤路由
 * @param { Array } routes 需要过滤的路由
 * @param { Array } powers 权限sn列表
 * @returns { Array }
 */
function filterAsyncRoutes(routes: RouteItem[], powers: string[]) {
  const res: RouteItem[] = []
  routes.forEach((route: RouteItem) => {
    const temp = { ...route } as RouteItem
    const sn = hasPermission(powers, temp)
    if (sn) {
      // 判断字符串获取排序值
      if (typeof sn === 'string') {
        const sort = sn.split(separator)[1]
        if (sort) {
          temp.meta.order = Number(sort)
        }
      }
      if (temp.children && temp.children.length) {
        temp.children = filterAsyncRoutes(temp.children, powers)
        if (temp.children.length) {
          res.push(temp)
        }
      } else {
        res.push(temp)
      }
    }
  })
  return res
}

// 排序
function sortRoutes(routes: RouteItem[]) {
  routes.forEach(route => {
    if (route.children) {
      route.children = sortRoutes(route.children)
    }
  })
  return routes.sort((a, b) => {
    return Number(a.meta?.order || 0) - Number(b.meta?.order || 0)
  }) as RouteItem[]
}

// 判断是否包括指定权限
function hasPermission(powers: string[], route: RouteItem) {
  if (route.meta && route.meta.sn) {
    const sn = powers.find(str => str.split(separator)[0] === route.meta.sn)
    return sn
  }
  return true
}

const routes: RouteItem[] = []
const addRoutes: RouteItem[] = []
export const useAuthStore = defineStore('auth', {
  state: () => ({
    routes,
    addRoutes
  }),

  actions: {
    // 生成路由
    generateRoutes(powers: string[]) {
      let accessRoutes: RouteItem[] = []
      if (powers.includes('ALL_SN')) {
        accessRoutes = asyncRoutes || []
      } else {
        accessRoutes = filterAsyncRoutes(asyncRoutes, powers)
      }

      this.addRoutes = sortRoutes(accessRoutes)
      this.routes = [...constantRoutes, ...accessRoutes] as RouteItem[]
      return accessRoutes
    }
  }
})
